package com.iw.adoms.service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import com.iw.adoms.dao.BrandDao;
import com.iw.adoms.entity.Brand;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.iw.adoms.entity.Department;
import com.iw.core.orm.Filtration;
import com.iw.core.orm.Filtration.MatchType;
import com.iw.core.orm.hibernate.BaseDao;
import com.iw.core.orm.hibernate.BaseService;

@Service
@Transactional
public class DepartmentService extends BaseService<Department> {

    @Resource
    private BrandDao brandDao;

    @Override
    @Resource(name = "departmentDao")
    public void setBaseDao(BaseDao<Department> baseDao) {
        this.baseDao = baseDao;
    }

    public List<Department> findByParentID(Integer pid) {
        return this.baseDao.findList(new Filtration(MatchType.EQ, pid, "department.id"));
    }

    /**
     * 保存或更新部门和其所代理的品牌
     *
     * @param d
     * @param ids
     */
    public void saveOrUpdate(Department d, Integer[] ids) {
        if (d.isNew()) {
            this.save(d);
        } else {
            this.update(d);
        }
        if (ids != null && ids.length > 0) {
            Set<Integer> idSet = new HashSet<Integer>();
            for(Integer id : ids) {
                idSet.add(id);
            }
            List<Brand> brands = brandDao.findAll();
            for (Brand b : brands) {
                if (idSet.contains(b.getId())) {
                    b.getDepartment().add(d);
                } else {
                    b.getDepartment().remove(d);
                }
                brandDao.update(b);
            }
        }
    }
}
